package com.example.lenovo.appstore.activity;

import androidx.appcompat.app.AlertDialog;
import androidx.core.content.FileProvider;
import androidx.recyclerview.widget.DefaultItemAnimator;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.OrientationHelper;
import androidx.recyclerview.widget.RecyclerView;
import butterknife.Bind;
import butterknife.ButterKnife;

import android.animation.ValueAnimator;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Color;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.util.Log;
import android.view.View;

import com.example.lenovo.adapter.AppInfoAdapter;
import com.example.lenovo.appstore.R;
import com.example.lenovo.appstore.base.BaseActivity;
import com.example.lenovo.appstore.utils.AppConfig;
import com.example.lenovo.appstore.utils.AppContext;
import com.example.lenovo.appstore.utils.DownLoadAPKUtil;
import com.example.lenovo.appstore.utils.StatusBarUtil;
import com.example.lenovo.appstore.view.MyDialog;
import com.example.lenovo.appstore.view.TitleBarView;
import com.example.lenovo.interfaca.DialogInterfaca;
import com.jiang.android.pbutton.CProgressButton;

import org.xutils.common.Callback;
import org.xutils.common.task.PriorityExecutor;
import org.xutils.http.RequestParams;
import org.xutils.x;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

public class AppInfoActivity extends BaseActivity implements View.OnClickListener {
    @Bind(R.id.appinfo_title)
    TitleBarView appinfo_title;
    @Bind(R.id.install)
    CProgressButton install;
    @Bind(R.id.appinfo_recyclerView)
    RecyclerView appinfo_recyclerView;
    Callback.Cancelable cancelable;
    private ProgressDialog progressDialog;
    ValueAnimator valueAnimator = null;
    private boolean isFinish=false;
    long total;
    long current;
    private AppInfoAdapter adapter;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_app_info);
        ButterKnife.bind(this);
        if(savedInstanceState!=null){
            total=savedInstanceState.getLong("total");
            current=savedInstanceState.getLong("current");
            Log.e("下载大小==","total="+total+"---current="+current);
        }
        initView();
        LinearLayoutManager layoutManager = new LinearLayoutManager(this );
//设置布局管理器
        appinfo_recyclerView .setLayoutManager(layoutManager);
//设置为垂直布局，这也是默认的
        layoutManager.setOrientation(OrientationHelper. HORIZONTAL);
//设置Adapter
        appinfo_recyclerView.setAdapter(adapter);
        //设置分隔线
//        appinfo_recyclerView.addItemDecoration( new SpacesItemDecoration(30 ));
//设置增加或删除条目的动画
        appinfo_recyclerView.setItemAnimator( new DefaultItemAnimator());
    }

    @Override
    protected void initView() {

        CProgressButton.initStatusString(new String[]{"下载","||","完成","error","delete"});
            install.normal(0);
        install.setTextColor(Color.BLACK);
        appinfo_title.setTitle(AppContext.getInstance().getResources().getString(R.string.productinfo));
        appinfo_title.showBackButton(true);
        StatusBarUtil.setStatusBarLightMode(getWindow());
        initListener();
        valueAnimator=ValueAnimator.ofInt(0,100);
        initData();
    }

    private void initData() {
        List<Integer> data=new ArrayList<Integer>();
        data.add(R.mipmap.info1);
        data.add(R.mipmap.info2);
        data.add(R.mipmap.info3);


        adapter=new AppInfoAdapter(data);

    }


    private void downLoadAPK(String url,String packageName){
//        执行网络请求操作

//        downLoad.setText("下载中...");
        RequestParams params = new RequestParams(url);
        params.setAutoRename(false);  //设置是否根据头信息命名文件
        params.setAutoResume(true);  //设置文件下载断点续传
        params.setExecutor(new PriorityExecutor(2,true));  //设置加载图片的线程池
        params.setCancelFast(true);  //设置是否可以立即停止
//        设置缓存的路径
        String filePath=AppContext.getInstance().getExternalFilesDir(null)+"/download/"+packageName+".apk";

//        if(new File(filePath).exists()){
//            //已存在  询问是否删除
//            AlertDialog.Builder builder = new AlertDialog.Builder(ProductInfoActivity.this);
//            builder.setTitle(getResources().getString(R.string.tishi)).setMessage(getResources().getString(R.string.quedinganzhuang))
//                    .setPositiveButton(getResources().getString(R.string.yes), new DialogInterface.OnClickListener() {
//                        @Override
//                        public void onClick(DialogInterface dialog, int which) {
////                              执行apk安装的步骤
//                            deleteSingleFile(filePath);
//
////                                deleteSingleFile(file.toString());
////                                Log.e("删除安装包==","删除成功");
//
//                        }
//                    }).setNegativeButton(getResources().getString(R.string.fail), new DialogInterface.OnClickListener() {
//            });
//            builder.create().show();
//
//        }else{
//
//        }
        params.setSaveFilePath(filePath);
        cancelable = x.http().get(params, new Callback.ProgressCallback<File>() {
            @Override
            public void onSuccess(final File file) {
                isStart=true;
//                请求成功时，回调的方法
                AlertDialog.Builder builder = new AlertDialog.Builder(AppInfoActivity.this);
                builder.setTitle(AppContext.getInstance().getResources().getString(R.string.tishi)).setMessage(AppContext.getInstance().getResources().getString(R.string.quedinganzhuang))
                        .setPositiveButton(AppContext.getInstance().getResources().getString(R.string.yes), new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
//                              执行apk安装的步骤
//                                downLoad.setImageResource(R.mipmap.download_apk_);
//                                downLoad.setClickable(true);
                                Intent intent = new Intent(Intent.ACTION_VIEW);
                                intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                                if(Build.VERSION.SDK_INT >= 24){//大于7.0
                                    Uri apkUri=FileProvider.getUriForFile(AppContext.getInstance(),"com.example.lenovo.appstore.fileprovider",file);
                                    //添加这一句表示对目标应用临时授权该Uri所代表的文件
                                    intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
                                    intent.setDataAndType(apkUri, "application/vnd.android.package-archive");
                                }else {
                                    intent.setDataAndType(Uri.fromFile(file), "application/vnd.android.package-archive");

                                }
                                AppInfoActivity.this.startActivity(intent);

//                                deleteSingleFile(file.toString());
//                                Log.e("删除安装包==","删除成功");

                            }
                        }).setNegativeButton(AppContext.getInstance().getResources().getString(R.string.fail), new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialogInterface, int i) {
//                        deleteSingleFile(file.toString());
                    }
                });
                builder.create().show();
            }
            @Override
            public void onError(Throwable throwable, boolean b) {
                Log.e("onError",throwable.getMessage().toString());
//              请求失败时，会执行的方法
            }
            @Override
            public void onCancelled(CancelledException e) {
                Log.e("onCancelled",e.getMessage().toString());
//              请求被取消时，会执行的方法
//                progressDialog.dismiss();
//                isStart=false;
                install.normal(1);
                valueAnimator.pause();

//                downLoad.setImageResource(R.mipmap.download_apk_);
//                downLoad.setClickable(true);
            }
            @Override
            public void onFinished() {
//              请求完成时，会执行的方法
                Log.e("onFinished","onFinished");
                if(isFinish){
                   install.normal(0);
                }else{
                    install.normal(1);
                }
//                install.normal(2);
//                install.setText("下载");
//                install.
            }
            @Override
            public void onWaiting() {
                Log.e("onWaiting","onWaiting");
//                downLoad.setImageResource(R.mipmap.download_apk_);
//                downLoad.setClickable(true);
            }
            @Override
            public void onStarted() {
                Log.e("onStarted","onStarted");
//                开始网络请求时，会执行的方法
                install.startDownLoad();
                valueAnimator.start();
//                CProgess(0);
            }
            @Override
            public void onLoading(long total, long current, boolean b) {
//                Log.e("total","onLoading=="+total);
//                Log.e("current","onLoading"+current);
//                Log.e("b","onLoading"+b);
                if(total==current){
                    isFinish=true;
                    isRunning=false;
                }else{
                    isFinish=false;
                    if(total!=current&&current>0) {
                        isRunning = true;
                    }
                }
                down_total=total;
                download_current=current;
//                  设置对话框当中的进度条
//                progressDialog.setProgress((int)(current*100/total));
               install.download((int)(current*100/total));

            }
        });

    }
DialogInterfaca interfaca;
    @Override
    protected void onPause() {
        super.onPause();
        Log.e("onpause==","onpause");

    }

    @Override
    protected void onStop() {
        super.onStop();
        if(isRunning){
            cancelable.cancel();
        }

        Log.e("onStop==","onStop");
    }

    private boolean isRunning;//是否存在下载任务
    long download_current;//已下载的大小
    long down_total;//总大小

    @Override
    protected void onRestart() {
        super.onRestart();
//        interfaca.finish(true);
//        interfaca=new DialogInterfaca() {
//            @Override
//            public void finish(boolean isFinished) {
//                if(isFinished) {
        Log.e("=======下载大小=",download_current+"");
        if(download_current>0&&download_current!=down_total||isRunning) {
            downLoadAPK("https://qd.myapp.com/myapp/qqteam/AndroidQQ/mobileqq_android.apk", "QQ");
        }
//                }

//            }
//        };
//
//                                DownLoadAPKUtil.downLoadAPK(valueAnimator,"QQ","https://qd.myapp.com/myapp/qqteam/AndroidQQ/mobileqq_android.apk",install,cancelable);
//        isStart = false;
        Log.e("onRestart==","onRestart");

    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        Log.e("onDestroy==","onDestroy");
    }

    @Override
    protected void initListener() {
        install.setOnClickListener(this);
    }
    boolean isStart=true;
    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.install:
                    if(isStart) {
                        MyDialog dialog=new MyDialog();
                        dialog.showDialog(AppInfoActivity.this, new DialogInterfaca() {
                            @Override
                            public void finish(boolean isFinished) {
                                if(isFinished){
//                                    isRunning=true;
                                    downLoadAPK("https://qd.myapp.com/myapp/qqteam/AndroidQQ/mobileqq_android.apk", "QQ");
//                                DownLoadAPKUtil.downLoadAPK(valueAnimator,"QQ","https://qd.myapp.com/myapp/qqteam/AndroidQQ/mobileqq_android.apk",install,cancelable);
                                    isStart = false;
                                    Log.e("====","onFinishi==");
                                }
                            }
                        });
                    }else{
                    Log.e("isStarted","false==");
                    install.normal(1);
//
//                        isRunning=false;
                    valueAnimator.pause();
                    cancelable.cancel();
                    isStart=true;
//
                }


                break;
        }
    }


    private void CProgess(final int value){
            if (install.getState() == CProgressButton.STATE.NORMAL) {

                install.startDownLoad();
                valueAnimator.setDuration(5000);
                valueAnimator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
                    @Override
                    public void onAnimationUpdate(ValueAnimator valueAnimator) {

                        if (value == 100) {
                            Log.e("完成===", "下载完成");
                            install.normal(2);


                        }
                        install.download(value);


                    }
                });

                valueAnimator.start();
            }
        else{

            Log.e("暂停===","暂停下载");
//                    valueAnimator.cancel();
            install.normal(1);

//            value= (int) valueAnimator.getAnimatedValue();
            valueAnimator.pause();

//                    install.normal(1);

        }
    }


}
